﻿using Domain.Event;
using Domain.IRepositorys;
using Domain.Model;
using Domain.Services;
using Domain.Types;
using Infrastructure.DomainEvent;
using Infrastructure.Error;
using Infrastructure.UniOfWorkBase;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OtherLib.AliPay;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utility;

namespace Application.Event
{
    /// <summary>
    /// 用户提现事件
    /// </summary>
    public class WithDrawEventHandler : IDomainEventHandler<WithDrawEvent>
    {
        public IWalletRepository walletRepository { get; set; }
        public IUserRepository userRepository { get; set; }
        public IWithDrawRepository withDrawRepository { get; set; }
        public MsgPulishService msgPulishService { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public WalletService walletService { get; set; }
        public ILogger<WithDrawEventHandler> _logger { get; set; }
        public override Task HandleAysnc(WithDrawEvent domainEvent, CancellationToken cancellationToken = default)
        {
            var w = withDrawRepository.Entities.First(i => i.Identity == domainEvent.WithDrawIdentity);

            if (w.Status != Domain.Types.WithDrawStatus.待打款) throw new BizException("当前转账状态不正确!");
            if (w.AuditStatus != WithDrawAuditStatus.机审通过 && w.AuditStatus != WithDrawAuditStatus.人审通过) throw new BizException("当前转账审核状态不正确!");

            w.Status = Domain.Types.WithDrawStatus.打款中;
            var serialNo = IDGeneratorUtil.GetId();
            w.BizNo = serialNo;

            efUnitOfWork.Commit();
            efUnitOfWork.Reset();
            var wallet = walletRepository.Entities.FirstOrDefault(i => i.UserID == w.UserID);

            switch (w.AccountType)
            {
                default:
                case Domain.Types.PayChannelEnum.支付宝:
                    {
                        //支付宝打款
                        var info = AliPayUtil.AliPayTransfer(serialNo.ToString(), wallet.AliPayAccount, wallet.AliPayAccountName, w.ReceiveMoney.ToString(), w.ID + "-" + DateTime.Now.ToString("yyyyMM"));
                        w.PayNO = info.order_id;
                        w.PayInfo = JsonConvert.SerializeObject(info);
                        w.ErrorMsg = info.sub_msg;
                        _logger.LogInformation($"转账ID:{w.ID} 转账到用户账号:{w.PayInfo}");

                        if (info.isError)
                        {
                            w.Status = Domain.Types.WithDrawStatus.打款失败;
                            //if (info.sub_msg.Contains("支付宝账号和姓名不匹配")
                            //                                || info.sub_msg.Contains("收款账号不存在")
                            //                                || info.sub_msg.Contains("请完善支付宝实名信息")
                            //                                || info.sub_msg.Contains("需要收款用户补充身份信息")
                            //                                || info.sub_msg.Contains("未完善身份信息或未开立余额账户"))
                            //{
                            //    //转账失败需要回退吗？
                            //    switch (w.WalletType)
                            //    {
                            //        default:
                            //        case WalletType.充值钱包:
                            //            walletService.ChangeChargeWallet(w.UserID,w.Money,-w.TaxFee,w.ID.ToString(),FinancialBizType.提现失败回退, "提现失败回退-充值钱包", "提现失败回退-充值钱包");
                            //            break;
                            //        case WalletType.佣金钱包:
                            //            walletService.ChangeInComeWallet(w.UserID, w.Money, -w.TaxFee, w.ID.ToString(), FinancialBizType.提现失败回退, "提现失败回退-发布钱包", "提现失败回退-发布钱包");
                            //            break;
                            //    }
                            //    w.Status = WithDrawStatus.转账失败退回;                                
                            //}
                            //else
                            {
                                //转人工处理
                                w.AuditStatus = WithDrawAuditStatus.待人工审核;
                                w.AuditOperator = null;
                            }

                        }
                        else
                        {
                            w.Status = Domain.Types.WithDrawStatus.打款成功;
                            msgPulishService.SendMsg(domainEvent.UserID, "提现成功", $"提现成功!");
                        }
                        efUnitOfWork.Commit();
                    }
                    break;
                case Domain.Types.PayChannelEnum.微信App:
                    {
                        throw new BizException("暂时不支持微信转账!");
                    }
            }


            return Task.CompletedTask;
        }
    }
}
